// sa
var sa = {};

// 打开loading
sa.loading = function(msg) {
	layer.closeAll();	// 开始前先把所有弹窗关了
	return layer.msg(msg, {icon: 16, shade: 0.3, time: 1000 * 20, skin: 'ajax-layer-load' });
};

// 隐藏loading
sa.hideLoading = function() {
	layer.closeAll();
};


// ----------------------------------- 登录事件 -----------------------------------

$('.login-btn').click(function(){
	sa.loading("正在登录...");
	// 开始登录
	setTimeout(function() {
		let username = $('[name=name]').val();
		let password = $('[name=pwd]').val();
		let encrypt = new JSEncrypt();
		let publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3oy3w1MgfUKhcZmckuVmzb9WNnNZYQ93J8Piw5paUFkNEpiqMLWOs0kQ6BrL9RecAfVdsIzJV/Qxr68p5iXEMS6Z3xzKjAtNs0kWP07GshcTLh+zXw9r99AE2HcFS0FB2KwBDmEADU4D2cJLXVVDjDsReREGkWvTYI4WAQ2ZPXBaRtd8wpgHqFCjeL6nFtUvsEciTy9mUFaCPclX4VHvhZlLiECn6I+vtaiEc0RrtAwAbpLqWfGQ41K3AsjJprHP4lrW+lyLKS1ZiuEdDbIV27CRJpO3UjuHdQ84Wv1zfIryYGgZiGwak43I5QpnRXZzigf/WraP2CIFnPUAoBonpQIDAQAB";
		encrypt.setPublicKey(publicKey);
		$('[name=pwd]').val(encrypt);
		let encryptPwd = encrypt.encryptLong(password);

		$.ajax({
			url: "/api/auth/sso/doLogin",
			type: "post",
			data: {
				name: username,
				pwd: encryptPwd
			},
			dataType: 'json',
			success: function(res){
				console.log('返回数据：', res);
				sa.hideLoading();
				if(res.code == 200) {
					layer.msg('登录成功', {anim: 0, icon: 6 });
					setTimeout(function() {
						let urlParams = location.search + location.hash;
						let strings = urlParams.split("?");
						for (const s of strings) {
							if(s.indexOf("redirect") > -1) {
								let  u = new URL(s.split("=")[1]);
								location.href = u.protocol + "//" + u.host + u.pathname + "?token=" + res.data.tokenValue + u.hash;
							}
						}
					}, 800)
				} else {
					layer.msg(res.msg, {anim: 6, icon: 2 });
				}
			},
			error: function(xhr, type, errorThrown){
				sa.hideLoading();
				if(xhr.status == 0){
					return layer.alert('无法连接到服务器，请检查网络');
				}
				return layer.alert("异常：" + JSON.stringify(xhr));
			}
		});
	}, 400);
});

// 绑定回车事件
$('[name=name],[name=pwd]').bind('keypress', function(event){
	if(event.keyCode == "13") {
		$('.login-btn').click();
	}
});

// 输入框获取焦点
$("[name=name]").focus();

// 打印信息
var str = "This page is provided by Sa-Token, Please refer to: " + "https://sa-token.cc/";
console.log(str);
